package com.ljl.rest;

import com.ljl.entity.FaceData;
import com.ljl.entity.FaceDetectResponse;
import com.ljl.entity.FaceGender;
import com.ljl.service.BaiduService;
import com.ljl.service.FaceDetectService;
import com.ljl.util.ImageTools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * @author 刘家良
 * @date 2022/10/30 16:17
 * @description
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class FaceDetectController {

    private final BaiduService baiduService;
    private final FaceDetectService faceDetectService;
    private final String tempFilePath = "temp";

    /**
     * 上传
     * @param fileUpload 图片资源
     * @return 图映射的虚拟访问路径
     */
    @PostMapping("/upload")
    public ResponseEntity<Object> upload(@RequestParam("file") MultipartFile fileUpload) {
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名。也可以在这里添加判断语句，规定特定格式的图片才能上传，否则拒绝保存。
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String[] fileType = new String[]{"jpg", "bmp", "png"};
        List<String> list = Arrays.asList(fileType);
        if (!list.contains(suffixName.toLowerCase(Locale.ROOT))) {
            return new ResponseEntity<>("格式不正确", HttpStatus.BAD_REQUEST);
        }
        File tempPath = new File(tempFilePath);
        if (!tempPath.exists()) {
            boolean mkdir = tempPath.mkdir();
            if ((!mkdir)) {
                return new ResponseEntity<>("文件夹创建失败", HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }
        try {
            String filePath = tempFilePath + File.separator + UUID.randomUUID() + "." + suffixName;
            //将图片保存
            fileUpload.transferTo(new File(filePath).getAbsoluteFile());
            //图片的base64字符串
            String imgBase64 = ImageTools.imgFileToBase64(filePath);
            //利用百度api获得人物关键点数据
            FaceDetectResponse response = baiduService.faceDetect(imgBase64);

            Integer faceNum = response.getFace_num();
            log.info("图片中人脸个数[{}]", faceNum);
            //处理图片
            List<FaceData> faceList = response.getFace_list();
            for (int i = 0; i < faceList.size(); i++) {
                FaceData faceData = faceList.get(0);
                log.info("==========第[{}]个人脸==========", i + 1);
                log.info("年龄[{}]", faceData.getAge());
                log.info("人脸可信度[{}]", faceData.getFace_probability());
                log.info("表情[{}],可信度[{}]", faceData.getEmotion().getType(), faceData.getEmotion().getProbability());
                log.info("心情[{}],可信度[{}]", faceData.getExpression(), faceData.getExpression().getProbability());
                log.info("性别[{}],可信度[{}]", faceData.getGender(), faceData.getGender().getProbability());
            }
            String outFileName = tempFilePath + File.separator + UUID.randomUUID() + "." + suffixName;
            faceDetectService.resolveImage(new File(filePath), faceList, new File(outFileName));
            //将处理好的图片返回
            return ResponseEntity.ok().body(ImageTools.imgFileToBase64(new File(outFileName).getAbsolutePath()));
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseEntity<>("系统异常", HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
